package com.lin.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName LoginFilter
 * @Description
 * @Author lin
 * @Date 2021/12/6 下午9:42
 * @Version V1.0
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("====================sos Filter=====================");
        // 需要强转后使用。
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 获取Session对象
        HttpSession session = httpRequest.getSession();
        // 从Session中获取用户登录的信息
        Object user = session.getAttribute("user");
        if (user == null) {
            // 说明用户还没有登录
            System.out.println("Filter中检查，用户没有登录。跳回登录页面");
            httpResponse.sendRedirect(httpRequest.getContextPath()
                    + "/login.html");
            return;
        } else {
            // 检查通过。放行
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
